﻿using System.Collections.Generic;
using UnityEngine;

namespace Super
{
	public class LangManager : BaseSingle<LangManager>
	{
		/// <summary>
		/// 管理器显示信息，方便调试
		/// </summary>
		[SerializeField]
		private int langIndex = 0;
		[Button("OnRefreshBtnClick")]
		public string refreshBtn = "刷新多语言";

		/// <summary>
		/// 多语言所有的keys
		/// 自定义keys和excel表格中的keys
		/// </summary>
		private HashSet<string> keys;
		public HashSet<string> Keys
		{
			get
			{
				if (keys == null)
				{
					keys = LangUtil.GetKeys();
				}
				return keys;
			}
		}

		/// <summary>
		/// 多语言文件信息列表
		/// </summary>
		[SerializeField]
		private List<LangFileInfo> fileList = new List<LangFileInfo>();
		public static List<LangFileInfo> FileList
		{
			get
			{
				if (Ins.fileList.Count != 0)
				{
					return Ins.fileList;
				}
				Ins.fileList = LangUtil.LoadFileList();

				return Ins.fileList;
			}
		}

		/// <summary>
		/// 初始化回调接口
		/// </summary>
		public override void OnInit()
		{
			base.OnInit();
			langIndex = GetCurIndex();
			fileList = LangUtil.LoadFileList();
		}

		/// <summary>
		/// 刷新按钮按下回调函数
		/// 设置新的多语言索引
		/// </summary>
		public void OnRefreshBtnClick()
		{
			SetCurIndex(langIndex);
			Refresh();
		}


		/// <summary>
		/// 获取多语言文本
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string GetText(string key)
		{
			string langText = key;
			string logInfo = "";
			LogType logType = LogType.Error;


			if (string.IsNullOrEmpty(key))//由于Lang组件生成时默认key为空字符，先屏蔽
			{
				//logType = LogType.Warn;
				//logInfo = "多语言key为空或者空字符不需要翻译，可以不需要Lang或LangFormat脚本";
			}
			else if (GetCurIndex() == 0)//默认多语言,直接使用key即可
			{
				if (!Ins.Keys.Contains(key))
				{
					logInfo = $"<color=#{ColorUtility.ToHtmlStringRGB(Color.red)}>{key}</color>不存在，请将相关配置文本添加到{DefaultConfig.customLangKeyPath}文件中\n" +
						$"{key}\n" +
						$"<a href=\"{DefaultConfig.customLangKeyPath}\">文件链接</a>";
				}
			}
			else
			{
				if (!FileList[GetCurIndex()].Data.keyValuePairs.TryGetValue(key, out langText))//没有时langText的值为null
				{
					langText = key;
					logInfo = $"<color=#{ColorUtility.ToHtmlStringRGB(Color.red)}>{key}</color>翻译不存在，请将相关配置文本添加到{LangUtil.GetCurPathOrAName()}文件中\n" +
						$"{key}\n" +
						$"<a href=\"{LangUtil.GetCurPathOrAName()}\">文件链接</a>";
				}
			}

			if (!string.IsNullOrEmpty(logInfo))
			{
				LogUtil.Log(logType, LogCategory.Lang, logInfo);
			}

			langText = langText.Replace("\\n", "\n");
			return langText;
		}

		/// <summary>
		/// 获取多语言文本的索引
		/// </summary>
		/// <returns></returns>
		public static int GetCurIndex()
		{
			return PlayerPrefs.GetInt($"{Application.productName}LangIndex", 0);
		}

		/// <summary>
		/// 设置多语言的索引
		/// </summary>
		/// <param name="index"></param>
		public static void SetCurIndex(int index)
		{
			if (0 > index || index >= FileList.Count)
			{
				LogUtil.Log(LogType.Error, LogCategory.Lang, $"index:{index}越界，LangListCount：{FileList.Count}");
				return;
			}
			else
			{
				PlayerPrefs.SetInt($"{Application.productName}LangIndex", index);
				Ins.langIndex = GetCurIndex();
				LogUtil.Log(LogType.Normal, LogCategory.Lang, $"设置多语言为：{FileList[index].name}");
			}
		}


		/// <summary>
		/// 添加自定义多语言Key
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static bool TryAddCustomKey(string key)
		{
			bool isReload = FWSetManager.GetSwitchState("CustomLangAddReload");
			if (isReload)
			{
#if UNITY_EDITOR
				Ins.keys = LangUtil.GetKeys();
#endif
			}

			bool isContain = Ins.Keys.Contains(key);
			if (isContain)
			{
				return false;
			}

			Ins.Keys.Add(key);
			LangUtil.AddKey(key, DefaultConfig.customLangKeyPath, DefaultConfig.templateCustomLangKeys);
			return true;
		}

		/// <summary>
		/// 调用所有继承ILangRefresh的MonoBehaviour对象的接口方法，刷新多语言文本
		/// </summary>
		public static void Refresh()
		{
			MonoBehaviour[] monoBehaviours = FindObjectsOfType<MonoBehaviour>();
			foreach (MonoBehaviour monoBehaviour in monoBehaviours)
			{
				if (monoBehaviour is ILangRefresh)
				{
					(monoBehaviour as ILangRefresh)?.OnLangRefresh();
				}
			}
		}
	}
}
